<?php
/**
*
* 功能描述（留言控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlLvmsg extends CtrlBase
{
	public $paramCheck = array(
		"add" => array(
			'type' => array("POST", "must", "intval", "positive"),
			'title' => array("POST", "must", "trim", "notempty"),
			'content' => array("POST", "must", "trim", "notempty"),
			'file' => array("FILES", "must", "", ""),
		),
	);

	public $perms = array(
		"add" => array(1, 255, "index.php?action=user.index"),
	);

	function Add()
	{
		$file = $this->params['file'];
		$name = $this->StoreFile($file);
		if($name === 1)
			$msg = "文件类型不支持";
		else if($name === 2)
			$msg = "文件大小超出限制";
		else if($name === 3)
			$msg = "上传错误";
		else if($name === 4)
			$msg = "存储错误";
		else
		{
			$data = array(
				'userid' => $this->user->userid,
				'username' => $this->user->username,
				'title' => $this->params['title'],
				'content' => $this->params['content'],
				'type' => $this->params['type'],
				'file' => $file['name'],
				'attach' => $name,
			);
			$obj = $this->GetModel("lvmsg");
			if($obj->NewMsg($data) <= 0)
				$msg = "留言失败";	//理论上调不到
			else
				$msg = "留言成功";
		}
		$this->assign("msg", $msg);
		return RT_MSG;
	}

	private function StoreFile($file)
	{
		if(empty($file['name']))
			return "";
		$type = $file['type'];
		$FILE_TYPES = array(
			'image/gif',
			'image/jpeg',
			'image/png',
			'application/vnd.ms-excel',
			'application/msword',
			'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
		);
		if(!in_array($type, $FILE_TYPES))
			return 1;
		if($file['size'] > 1024 * 1024 * 1024)
			return 2;
		if($file['error'] > 0)
			return 3;
		$filename = UPLOAD_DIR . time() . "_" .  $this->user->userid . "." . pathinfo($file['name'], PATHINFO_EXTENSION);
		if(!move_uploaded_file($file['tmp_name'], $filename))
			return 4;
		else
			return $filename;
	}
}

